﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace SinaWeiboApp_sl.Command
{
    public static class TextChanged {
        private static readonly DependencyProperty TextBoxTextChangedCommandBehaviorProperty = DependencyProperty.RegisterAttached(
            "TextBoxTextChangedCommandBehavior",
            typeof(TextBoxTextChangedCommandBehavior),
            typeof(TextChanged),
            null);

        public static readonly DependencyProperty TextBoxTextChangedCommandProperty = DependencyProperty.RegisterAttached(
            "Command",
            typeof(ICommand),
            typeof(TextChanged),
            new PropertyMetadata(OnSetCommandCallback));

        public static void SetCommand(TextBox textBox, ICommand command) {
            textBox.SetValue(TextBoxTextChangedCommandProperty, command);
        }

        public static ICommand GetCommand(TextBox textBox) {
            return textBox.GetValue(TextBoxTextChangedCommandProperty) as ICommand;
        }

        private static void OnSetCommandCallback(DependencyObject sender, DependencyPropertyChangedEventArgs e) {
            TextBox textBox = sender as TextBox;
            if (textBox != null) {
                var behavior = GetOrCreateCommandBehavior(textBox);
                behavior.Command = e.NewValue as ICommand;
            }
        }

        private static TextBoxTextChangedCommandBehavior GetOrCreateCommandBehavior(TextBox textBox) {
            var behavior = textBox.GetValue(TextBoxTextChangedCommandBehaviorProperty) as TextBoxTextChangedCommandBehavior;
            if (behavior == null) {
                behavior = new TextBoxTextChangedCommandBehavior(textBox);
                textBox.SetValue(TextBoxTextChangedCommandBehaviorProperty, behavior);
            }
            return behavior;
        }
    }
}
